﻿var m_Map;
//初始百度地图
function InitBaiduMap(city, zoom, div, tool) {
    if (m_Map == null) {
        m_Map = new BMap.Map(div);               // 创建Map实例
    }
    m_Map.centerAndZoom(city, zoom);
    m_Map.addControl(new BMap.NavigationControl());   // 添加平移缩放控件  
    m_Map.addControl(new BMap.ScaleControl());        // 添加比例尺控件  
    m_Map.addControl(new BMap.OverviewMapControl());  //添加缩略地图控件  
    m_Map.addControl(new BMap.MapTypeControl());      //添加地图类型控件  
    m_Map.enableScrollWheelZoom();                    //启用滚轮放大缩小
    m_Map.addEventListener("dblclick", ZoomIn);
    if (tool == true) {
        OpenDrawingManager();
    }
}
//放大地图一级
function ZoomIn() {
    m_Map.zoomIn();
}
/*==================实时监控=====================*/
var markerMap = {};
var infoWindowMap = {};
//增加标注点
function AddMarker(info) {
    if (info.lng == null || info.lat == null || info.lng == "" || info.lat == "") {
        return;
    }
    var img = GetVehilceImg(info.gpsSpeed,info.dire);
    var icon = new BMap.Icon(img, new BMap.Size(25, 25));
    var point = new BMap.Point(info.lng, info.lat);
    var marker = new BMap.Marker(point, { icon: icon });
    var label = new BMap.Label(info.name);
    label.setOffset(new BMap.Size(-17, 25));
    label.setStyle({ color: "white", backgroundColor: "#007898", border: "none", textAlign: "center", width: "60px" });
    marker.setLabel(label);
    marker.setTitle(name);

    var infoWindow = new BMap.InfoWindow(GetInfoWindowHtml(info), {
        offset: new BMap.Size(0, -15),
        enableMessage: false
    }); // 创建信息窗口对象    
    marker.addEventListener("click", function () {
        this.openInfoWindow(infoWindow);      // 打开信息窗口 
    });
    marker.addEventListener("mouseover", function () {
        marker.setTop(true);
    });
    marker.addEventListener("mouseout", function () {
        marker.setTop(false);
    });
    marker.addEventListener("infowindowclose", function () {
        infoWindowMap[info.sim].open = false;
    });
    marker.addEventListener("infowindowopen", function () {
        infoWindowMap[info.sim].open = true;
    });

    m_Map.addOverlay(marker);

    markerMap[info.sim] = marker;
    infoWindowMap[info.sim] = {
        open: false,
        infoWindow: infoWindow
    };
}
function AddMarkers(infos) {
    for (var i = 0; i < infos.length; i++) {
        var info = info[i];
        if (info.lng == null || info.lat == null || info.lng == "" || info.lat == "") {
            return;
        }
        var img = GetVehilceImg(info.gpsSpeed, info.dire);
        var icon = new BMap.Icon(img, new BMap.Size(25, 25));
        var point = new BMap.Point(info.lng, info.lat);
        var marker = new BMap.Marker(point, { icon: icon });
        var label = new BMap.Label(info.name);
        label.setOffset(new BMap.Size(-17, 25));
        label.setStyle({ color: "white", backgroundColor: "#007898", border: "none", textAlign: "center", width: "60px" });
        marker.setLabel(label);
        marker.setTitle(name);

        var infoWindow = new BMap.InfoWindow(GetInfoWindowHtml(info), {
            offset: new BMap.Size(0, -15),
            enableMessage: false
        }); // 创建信息窗口对象    
        marker.addEventListener("click", function () {
            this.openInfoWindow(infoWindow);      // 打开信息窗口 
        });
        marker.addEventListener("mouseover", function () {
            marker.setTop(true);
        });
        marker.addEventListener("mouseout", function () {
            marker.setTop(false);
        });
        marker.addEventListener("infowindowclose", function () {
            infoWindowMap[info.sim].open = false;
        });
        marker.addEventListener("infowindowopen", function () {
            infoWindowMap[info.sim].open = true;
        });
        markerMap[info.sim] = marker;
        infoWindowMap[info.sim] = {
            open: false,
            infoWindow: infoWindow
        };
        m_Map.addOverlay(marker);
    }
}
//删除标注点
function DelMarker(info) {
    if (info.lng == null || info.lat == null || info.lng == "" || info.lat == "") {
        return;
    }
    m_Map.removeOverlay(markerMap[info.sim]);
    markerMap[info.sim] = null;
    infoWindowMap[info.sim] = null;
}
//修改标注点
function ModMarker(info) {
    if (info.lng == null || info.lat == null || info.lng == "" || info.lat == "") {
        return;
    }
    var marker = markerMap[info.sim];
    if (marker == null) {
        AddMarker(info);
        return;
    }
    marker.setPosition(new BMap.Point(info.lng, info.lat));
    marker.setIcon(new BMap.Icon(GetVehilceImg(info.gpsSpeed,info.dire), new BMap.Size(25, 25)));
    var infoWindowJson = infoWindowMap[info.sim];
    infoWindowJson.infoWindow.setContent(GetInfoWindowHtml(info));
    if (infoWindowJson.open == true) {
        marker.openInfoWindow(infoWindowJson.infoWindow);
    }
}
//获得标注的焦点
function FocusMarker(info) {
    var marker = markerMap[info.sim];
    if (marker != null) {
        m_Map.panTo(marker.getPosition());
        marker.openInfoWindow(infoWindowMap[info.sim].infoWindow);
    }
    else {
        artDialogAlert("没有《" + info.name + "》的最新GPS信息");
    }
}

/*画区域*/
function addRegion(lng, lat, radius, name) {
    if (m_Map == null) {
        m_Map = new BMap.Map("MapDiv");               // 创建Map实例
    }
    var point = new BMap.Point(lng, lat);
    var circle = new BMap.Circle(point, radius, {
        strokeColor: "red",     //圆边线颜色
        fillColor: "red",       //填充颜色
        fillOpacity: 0.35,      //填充透明度
        strokeWeight: 2  //边线宽度
    });
    var hoffset = 0;
    var m = /[\u4E00-\u9FA5]/;
    for (var i = 0; i < name.length; i++) {
        var ch = name[i];
        if (m.test(ch)) {
            hoffset += 13;
        }
        else {
            hoffset += 7;
        }
    }
    var label = new BMap.Label(name, { offset: new BMap.Size(-hoffset/2, -8), position: point });
    label.setStyle({ color: "white", backgroundColor: "#ff7851", border: "1px white solid"});
    m_Map.addOverlay(label);
    m_Map.addOverlay(circle);
}
/*==================实时监控=====================*/



/*==================车辆跟踪=====================*/
var trackMarkerMap = {};
var trackInfoWindow = {};
var prePoint;
function AddTrackMarker(info){
    if (info.lng == null || info.lat == null || info.lng == "" || info.lat == "") {
        return;
    }
    var img = GetVehilceImg(info.gpsSpeed,info.dire);
    var icon = new BMap.Icon(img, new BMap.Size(25, 25));
    var point = new BMap.Point(info.lng, info.lat);
    var marker = new BMap.Marker(point, { icon: icon });
    var label = new BMap.Label(info.name);
    label.setOffset(new BMap.Size(-17, 25));
    label.setStyle({ color: "white", backgroundColor: "#007898", border: "none", textAlign: "center", width: "60px" });
    marker.setLabel(label);
    marker.setTitle(name);

    var infoWindow = new BMap.InfoWindow(GetInfoWindowHtml(info), {
        offset: new BMap.Size(0, -15),
        enableMessage: false
    }); // 创建信息窗口对象    
    marker.addEventListener("click", function () {
        this.openInfoWindow(infoWindow);      // 打开信息窗口 
    });
    marker.addEventListener("mouseover", function () {
        marker.setTop(true);
    });
    marker.addEventListener("mouseout", function () {
        marker.setTop(false);
    });

    m_Map.addOverlay(marker);
    /*画轨迹*/
    if (prePoint != null) {
        var points = new Array();
        points.push(prePoint);
        points.push(point);
        var polyline = new BMap.Polyline(points, { strokeColor: "#5b849e", strokeWeight: 5, strokeStyle: "solid" });
        m_Map.addOverlay(polyline);
    }
    m_Map.panTo(point);

    trackMarkerMap[info.time] = marker;
    trackInfoWindow[info.time] = infoWindow;
    prePoint = point;
}
//关闭信息窗口
function TrackFocusMarker(info) {
    var marker = trackMarkerMap[info.time];
    if (marker != null) {
        m_Map.panTo(marker.getPosition());
        marker.openInfoWindow(trackInfoWindow[info.time]);
    }
}
//移除所有的轨迹以及标注点
function ClearTrackMarker() {
    trackMarkerMap = {};
    trackInfoWindow = {};
    m_Map.clearOverlays();
}
/*==================车辆跟踪=====================*/



/*==================轨迹回放=====================*/
var backPoints = [];//所有点
var backMarkers = [];
var backInfoWindows = [];
var backFocusMarker;//焦点标注
var backFocusInfoWindow;//焦点信息窗口
var backMoveMarker;//移动的标注
var backMoveInfoWindow;//移动标注的信息窗口
var backCurIndex = 0;//当前播放的索引
var backInterval;//播放定时器
var backSpeed = 5;//播放速度
var isPaintPath;//是否画轨迹
/*重置参数*/
function ResetTrackBack() {
    backPoints = [];
    backMarkers = [];
    backInfoWindows = [];
    backMoveMarker = null;
    backMoveInfoWindow = null;
    backCurIndex = 0;
    clearInterval(backInterval);
    m_Map.clearOverlays();
}
/*设置播放速度*/
function SetSpeed(speed,isPlay) {
    backSpeed = speed;
    if (isPlay == 1) {
        PauseTrackBack();
        ContinueTrackBack();
    }
}
function InitTrackBack(infos,paintPath) {
    ResetTrackBack();
    isPaintPath = paintPath;
    for (var i = 0; i < infos.length; i++) {
        var info = infos[i];
        if (info.lng == null || info.lat == null ||
            info.lng == "" || info.lat == "") {
            continue;
        }
        var mi = CreateBackMarkerAndInfoWindow(info);
        backMarkers.push(mi.marker);
        backInfoWindows.push(mi.infoWindow);
        backPoints.push(mi.point);

        if (isPaintPath == true) {
            if (i % 10 == 0) {//十个点画一个标注
                //var simg = GetVehilceStaticImg(null, info.dire);
                //var sicon = new BMap.Icon(simg, new BMap.Size(25, 25));
                //var smarker = new BMap.Marker(point, { icon: sicon });
                //smarker.addEventListener("click", function () {
                //    this.openInfoWindow(infoWindow);
                //});
                //smarker.addEventListener("mouseover", function () {
                //    this.setTop(true);
                //});
                //smarker.addEventListener("mouseout", function () {
                //    this.setTop(false);
                //});
                //m_Map.addOverlay(smarker);
            }
        }
    }
    if (isPaintPath == true) {
        var polyline = new BMap.Polyline(
            backPoints,
            {
                strokeColor: "#5b849e",
                strokeWeight: 5,
                strokeStyle: "solid"
            });
        m_Map.addOverlay(polyline);
    }
    m_Map.setCenter(backPoints[0]);
}
/*创建marker*/
function CreateBackMarkerAndInfoWindow(info) {
    var point = new BMap.Point(info.lng, info.lat);
    var img = GetVehilceImg(info.gpsSpeed, info.dire);
    var icon = new BMap.Icon(img, new BMap.Size(25, 25));
    var marker = new BMap.Marker(point, { icon: icon });
    var infoWindow = new BMap.InfoWindow(GetInfoWindowHtml(info), {
        offset: new BMap.Size(0, -15),
        enableMessage: false
    }); // 创建信息窗口对象    
    marker.addEventListener("click", function () {
        this.openInfoWindow(infoWindow);      // 打开信息窗口 
    });
    marker.addEventListener("mouseover", function () {
        marker.setTop(true);
    });
    marker.addEventListener("mouseout", function () {
        marker.setTop(false);
    });
    return {
        marker: marker,
        point:point,
        infoWindow: infoWindow
    };
}
/*双击数据行获取焦点*/
function FocusBackMarker(index) {
    var marker = backMarkers[index];
    var infoWindow = backInfoWindows[index];   
    if (marker != null) {
        if (backFocusMarker != null) {
            m_Map.removeOverlay(backFocusMarker);
        }
        m_Map.addOverlay(marker);
        m_Map.panTo(marker.getPosition());
        marker.openInfoWindow(infoWindow);
        backFocusMarker = marker;
        backFocusInfoWindow = infoWindow;
    }
}
/*设置移动标注*/
function SetMoveMarker() {
    if (backMoveMarker != null) {
        //移除上一个标注点
        m_Map.removeOverlay(backMoveMarker);
    }
    //添加当前标注点到地图并地图中心移动到该标注点
    backMoveMarker = backMarkers[backCurIndex];
    m_Map.addOverlay(backMoveMarker);
    m_Map.panTo(backMoveMarker.getPosition());

    if (isPaintPath == false && backCurIndex != 0) {
        /*边移动边画轨迹*/
        var points = new Array();
        points.push(backPoints[backCurIndex - 1]);
        points.push(backPoints[backCurIndex]);
        var polyline = new BMap.Polyline(points, { strokeColor: "#5b849e", strokeWeight: 5, strokeStyle: "solid" });
        m_Map.addOverlay(polyline);
    }
    

    FocusRow(backCurIndex);
    backCurIndex++;
    if (backCurIndex == backMarkers.length) {//播放结束
        StopTrackBack();
        artDialogAlert("历史轨迹播放结束");
    }
}
/*更新标注窗口*/
function UpdateBackInfoWindow(index, info) {
    var infoWindow = backInfoWindows[index];
    infoWindow.setContent(GetInfoWindowHtml(info));
}
/*开始播放*/
function StartTrackBack() {
    if (isPaintPath == false) {
        m_Map.clearOverlays();
    }
    backInterval = setInterval("SetMoveMarker()", (11 - backSpeed) * 200);
}
/*暂停播放*/
function PauseTrackBack() {
    clearInterval(backInterval);
}
/*停止播放*/
function StopTrackBack() {
    backMoveMarker = null;
    backMoveInfoWindow = null;
    clearInterval(backInterval);
    backCurIndex = 0;
    m_Map.setCenter(backPoints[0]);
}
/*继续播放*/
function ContinueTrackBack() {
    backInterval = setInterval("SetMoveMarker()", (11 - backSpeed) * 200);
}
/*设置是否绘制地图*/
function SetPaintPath(value) {
    isPaintPath = value;
    m_Map.clearOverlays();
    if (isPaintPath == true) {
        var polyline = new BMap.Polyline(
            backPoints,
            {
                strokeColor: "#5b849e",
                strokeWeight: 5,
                strokeStyle: "solid"
            });
        m_Map.addOverlay(polyline);
    }
}
/*==================轨迹回放=====================*/





/*==================地图工具=====================*/
var overlays = [];
var drawingManager;
//回调获得覆盖物信息
var overlaycomplete = function (e) {
    var cal = e.calculate;
    var label = e.label;
    if (e.drawingMode == BMAP_DRAWING_POLYLINE ){//划线
        var cal = (parseFloat(cal) / 1000).toFixed(2) + "公里";
    }
    if (e.drawingMode == BMAP_DRAWING_CIRCLE ||
        e.drawingMode == BMAP_DRAWING_POLYGON ||
        e.drawingMode == BMAP_DRAWING_RECTANGLE) {
        var cal = (parseFloat(cal) / 1000000).toFixed(2) + "平方公里";
    }
    label.setContent(cal);
    overlays.push(e.overlay);
    overlays.push(label);
};

//打开地图工具
function OpenDrawingManager() {
    var styleOptions = {
        strokeColor: "red",    //边线颜色。
        fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 2,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
        fillOpacity: 0.5,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }
    //实例化鼠标绘制工具
    drawingManager = new BMapLib.DrawingManager(m_Map, {
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_LEFT, //位置
            offset: new BMap.Size(80, 10), //偏离值
            scale: 0.55, //工具栏缩放比例
            drawingModes: [BMAP_DRAWING_CIRCLE, BMAP_DRAWING_POLYLINE, BMAP_DRAWING_POLYGON, BMAP_DRAWING_RECTANGLE]
        },
        
        circleOptions: styleOptions, //圆的样式
        polylineOptions: styleOptions, //线的样式
        polygonOptions: styleOptions, //多边形的样式
        rectangleOptions: styleOptions //矩形的样式
    });
    //添加鼠标绘制工具监听事件，用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
    //打开进行线或面积的计算（单位米）
    drawingManager.enableCalculate();
    drawingManager.open()
    drawingManager.close();
}
//清除所有绘图
function ClearOverlays() {
    for (var i = 0; i < overlays.length; i++) {
        m_Map.removeOverlay(overlays[i]);
    }
    overlays = [];
}
//清除最后一个绘图
function ClearLastOverlay() {
    if (overlays.length >= 2) {
        m_Map.removeOverlay(overlays.pop());
        m_Map.removeOverlay(overlays.pop());
    }
}
/*==================地图工具=====================*/

/*==================辅助函数=====================*/
//获取车辆方向和状态图片
function GetVehilceImg(speed, dire) {
    if (speed == "0") {
        return "/Images/park.png";
    }
    if (dire == "正东") {
        return "/Images/moveeast.png";
    }
    else if (dire == "正西") {
        return "/Images/movewest.png";
    }
    else if (dire == "正南") {
        return "/Images/movesouth.png";
    }
    else if (dire == "正北") {
        return "/Images/movenorth.png";
    }
    else if (dire == "东北") {
        return "/Images/movenortheast.png";
    }
    else if (dire == "东南") {
        return "/Images/movesoutheast.png";
    }
    else if (dire == "西北") {
        return "/Images/movenorthwest.png";
    }
    else{// (dire == "西南") {
        return "/Images/movesouthwest.png";
    }
}
//获取infowindow显示的内容
function GetInfoWindowHtml(info) {
    var ret = "";
    ret += "<table style='font-family:verdana;font-size:12;color:black;'>";
    ret += "<tr><td>车牌号：</td><td>";
    ret += info.name + "</td></tr>";
    ret += "<tr><td>ACC状态：</td><td>";
    ret += info.state0 + "</td></tr>";
    ret += "<tr><td>电量(百分比)：</td><td>";
    ret += info.battery + "</td></tr>";
    ret += "<tr><td>上传时间：</td><td>";
    ret += info.time + "</td></tr>";
    ret += "<tr><td>速度：</td><td>";
    ret += info.gpsSpeed + "</td></tr>";
    ret += "<tr><td>行驶方向：</td><td>";
    ret += info.dire + "</td></tr>";
    ret += "<tr><td>当前位置：</td><td>";
    ret += info.addr + "</td></tr>";
    ret += "</table>";
    return ret;
}

//获取车辆方向和状态图片(轨迹回放静态点)
function GetVehilceStaticImg(speed, dire) {
    if (speed == "0") {
        return "/Images/park.png";
    }
    if (dire == "正东") {
        return "/Images/east.png";
    }
    else if (dire == "正西") {
        return "/Images/west.png";
    }
    else if (dire == "正南") {
        return "/Images/south.png";
    }
    else if (dire == "正北") {
        return "/Images/north.png";
    }
    else if (dire == "东北") {
        return "/Images/northeast.png";
    }
    else if (dire == "东南") {
        return "/Images/southeast.png";
    }
    else if (dire == "西北") {
        return "/Images/northwest.png";
    }
    else {// (dire == "西南") {
        return "/Images/southwest.png";
    }
}
/*==================辅助函数=====================*/